<?php

defined('is_running') or die('Not an entry point...');

function readData($filename) {
  $fh = fopen($filename, 'r');
  if (!$fh)
    exit("unable to open file ($filename)");

  while (!feof($fh))
    $lines[] = trim(fgets($fh));
  fclose($fh);
  unset($lines[count($lines) - 1]); // remove last \n

  return $lines;
}

function writeData($file_data, $lines, $attr) {
  $fh = fopen($file_data, $attr);
  foreach ($lines as $line)
    fwrite($fh, $line . "\n");
  fclose($fh);
}

function isDateValid($new_date) {
  // checks if date in YYYY-MM-DD format
  $result = TRUE;
  $new_date = htmlentities($new_date);

  if (strlen($new_date) == 10) {
    $yyyy = substr($new_date, 0, 4);
    $mm = substr($new_date, 5, 2);
    $dd = substr($new_date, 8, 2);

    if (is_numeric($yyyy) && is_numeric($mm) && is_numeric($dd) &&
            (substr($new_date, 4, 1) === "-") && (substr($new_date, 7, 1) === "-")) {
      if (!checkdate($mm, $dd, $yyyy)) {
        $result = FALSE;
      }
    } else {
      $result = FALSE;
    }
  } else {
    $result = FALSE;
  }

  return $result;
}

function addFavourites($fav_name, $fav_url, $fav_cat, $fav_date) {
  require("init.php");
  $lines = readData($fav_data);

  if (count($lines) > 0) { // if file is not empty
    list($last_fav_id) = explode("|", $lines[count($lines) - 1]); // take last $fav_id
    $new_fav_id = $last_fav_id + 1;
  } else {
    $new_fav_id = 0;
  }

  $last_line[] = "$new_fav_id|$fav_name|$fav_url|$fav_cat|$fav_date";
  writeData($fav_data, $last_line, 'a');
}

function delFavourites($fav_id) {
  require("init.php");
  $lines = readData($fav_data);

  for ($i = 0; $i < count($lines); $i++) {
    list($delrow) = explode("|", $lines[$i]);

    if (strcmp($delrow, $fav_id) == 0)
      $unset_i = $i;
  }
  unset($lines[$unset_i]);

  writeData($fav_data, $lines, 'w');
}

function addCategories($cat_name) {
  require("init.php");
  $lines = readData($cat_data);

  if (count($lines) > 0) { // if file is not empty
    list($last_cat_id) = explode("|", $lines[count($lines) - 1]); // take last $cat_id
    $new_cat_id = $last_cat_id + 1;
  } else {
    $new_cat_id = 0;
  }

  $last_line[] = "$new_cat_id|$cat_name";
  writeData($cat_data, $last_line, 'a');
}

function delCategories($cat_id) {
  require("init.php");
  $lines = readData($cat_data);

  for ($i = 0; $i < count($lines); $i++) {
    list($delrow) = explode("|", $lines[$i]);

    if (strcmp($delrow, $cat_id) == 0)
      $unset_i = $i;
  }
  unset($lines[$unset_i]);

  writeData($cat_data, $lines, 'w');
}

?>
